package com.vhly.ddxdecompiler.dexreader.file;

import com.vhly.ddxdecompiler.dexreader.file.mixeditem.StringDataItem;
import com.vhly.ddxdecompiler.dexreader.file.mixeditem.StringIdItem;
import com.vhly.ddxdecompiler.dexreader.io.DexInputStream;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: vhly
 * Date: 2009-10-14
 * Time: 17:19:24
 *
 * @author vhly[FR]
 */
public class StringIdsSection extends Section {
    private int size;
    private int offset;

    private Vector<StringIdItem> items;
    private DexFile dex;

    public StringIdsSection(DexFile dexFile) {
        items = new Vector<StringIdItem>();
        size = -1;
        offset = -1;
        name = "string_ids";
        dex = dexFile;
    }

    public void read(DexInputStream din) throws IOException {

        // debug
        int offset = din.getOffset();
//        System.out.println("StringIdsSection offset = " + offset);

        int c = size;
        if (c > 0) {
            StringIdItem item;
            for (int i = 0; i < c; i++) {
                item = new StringIdItem(dex);
                item.read(din);
                items.addElement(item);
            }
        }
    }

    public void write(DataOutputStream dout) {
    }

    public void readHeaderPart(DexInputStream din) throws IOException {
        size = din.readInt();
        offset = din.readInt();
        dex.offsetCache.put(Integer.toString(offset), this);
    }

    public StringIdItem indexOf(int index) {
        StringIdItem ret = null;
        if (index >= 0) {
            ret = items.elementAt(index);
        }
        return ret;
    }

    public void reloc(ByteArrayInputStream bin, int offset) throws IOException {
        bin.reset();
        DataInputStream din = new DataInputStream(bin);
        DexInputStream dxin = new DexInputStream(din, 1);
        StringIdItem item;
        int size = items.size();
        StringDataItem ditem;
        for (int i = 0; i < size; i++) {
            item = items.elementAt(i);
            int off = item.dataOffset;
            bin.skip(off - offset);
            dxin.setOffset(off);
            ditem = new StringDataItem(dex);
            ditem.read(dxin);
            item.setDataItem(ditem);
            bin.reset();
            dxin.setOffset(offset);
        }
        dxin.close();
        din.close();
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("Section{ name=").append(name).append("size=").append(size).append("}");
        return sb.toString();
    }
}
